<?php
namespace app\controller;

use app\BaseController;
use app\controller\ForwardController;
use app\model\ElevatorAlarmNdata;
use app\model\ElevatorAlarmRdata;
use app\model\ElevatorNdata;
use app\model\ElevatorRdata;
use app\model\TowerAlarmNdata;
use app\model\TowerAlarmRdata;
use app\model\TowerCraneNdata;
use app\model\TowerCraneRdata;
use app\model\TowerCraneWorkData;
use think\facade\Log;
use think\Request;

//use think\facade\Db;

/* 文档 */
//转发数据携带转发id
//创建（Create）、更新（Update）、读取（Retrieve）和删除（Delete）。

/* HTTP方式数据接入 */
class RealTimeDataController extends BaseController
{
    public function createData()
    {
        $header_dataType = $this->request->header('dataType'); //获取设备类型
        /* 已存在的设备类型 */
        $dataType = ['TowerCrane', 'Elevator'];
        if (!in_array($header_dataType, $dataType)) {
            return fail(null, '没有该设备类型');
        }
        $request = $this->request->param();
        /* 定义模型 */
        $rdataModelName = 'app\model\\' . $header_dataType . 'Rdata';
        $rdataModel = new $rdataModelName; //实时数据
        /* -------------- */
        $ndataModelName = 'app\model\\' . $header_dataType . 'Ndata';
        $ndataModel = $ndataModelName::where('eid', $request['eid'])->find(); //最新一条数据
        if (!$ndataModel) {
            $ndataModel = new $ndataModelName; //最新数据
            //增加必要设备参数 减少查询次数
        }
        foreach ($request as $key => $value) {
            $value = round($value,2);
            $rdataModel->$key = $value;
            $ndataModel->$key = $value;
        }
        $re = $rdataModel->save();
        $ndataModel->update_time = date('Y-m-d H:i:s', time());
        $re = $ndataModel->save();
        /* 数据转发其他平台 */
        if ($ndataModel->forward_id) {
            $f_re = ForwardController::forward($ndataModel->toArray());
        }
        if ($re) {
            return success(['issued_control' => $ndataModel->issued_control]);
        } else {
            return fail(null, '写入数据失败');
        }

    }
    public function createAlarmData()
    {
        // Log::write($this->request->param(), 'request');
        $header_dataType = $this->request->header('dataType'); //获取设备类型
        /* 已存在的设备类型 */
        $dataType = ['TowerAlarm', 'ElevatorAlarm'];
        if (!in_array($header_dataType, $dataType)) {
            return fail(null, '没有该报警设备类型');
        }
        $request = $this->request->param();
        /* 定义模型 */
        $rdataModelName = 'app\model\\' . $header_dataType . 'Rdata';
        $rdataModel = new $rdataModelName; //实时数据
        /* -------------- */
        $ndataModelName = 'app\model\\' . $header_dataType . 'Ndata';
        $ndataModel = $ndataModelName::where('eid', $request['eid'])->find(); //最新一条数据
        if (!$ndataModel) {
            $ndataModel = new $ndataModelName; //最新数据
            //增加必要设备参数 减少查询次数
        }
        foreach ($request as $key => $value) {
            $value = round($value,2);
            $rdataModel->$key = $value;
            $ndataModel->$key = $value;
        }
        /* ---数据写入--- */
        try {
            $re = $rdataModel->save();
            $re = $ndataModel->save();
        } catch (\Exception $e) {
            return fail(null, $e->getMessage());
        }

        /* 数据转发其他平台 */
        if ($ndataModel->forward_id) {
            $f_re = ForwardController::alarmForward($ndataModel->toArray());
        }
        if ($re) {
            return success('success');
        } else {
            return fail(null, '写入数据失败');
        }

    }
    public static function tcpTowerData($param, $client_id)
    {
        //拆分信息字段
        $head = substr($param, 0, 4);
        $length = substr($param, 4, 2); //帧长度 全部长度总和
        $code = substr($param, 6, 2);
        $edition = substr($param, 8, 2); //协议版本
        $type = substr($param, 10, 2); //帧类型
        $eid = substr($param, 12, 8);
        $info = substr($param, 20, -10); //信息段
        $sum = substr($param, -10, 2); //校验和剔除sum end后的长度
        $end = substr($param, -8);
        switch ($type) {
            case '00': //帧类型 设备注册请求帧上传
                //A5 5A 0F 00 00 00 00 00 39 36 -- 7D CC33C33C
                //A5 5A 16 00 00 01 00 00 39 36 16 09 1D 11 00 05 0A e1 CC33C33C
                //A5 5A 16 00 00 01 00 00 39 36 -- 16 09 1D 10 34 09 0A 21 -- 8C C33C33C
                Log::write('-head:' . $head . '-length:' . $length . '-code:' . $code . '-edition:' . $edition . '-type:' . $type . '-eid:' . $eid . '-sum:' . $sum . '-end:' . $end, 'TCP_TOWER_register');
                $time = date('ymdHis', time()); //获取当前时间 转化为 年(2位)月日时分秒
                $array_time = str_split($time, 2); //截取两个一组
                foreach ($array_time as $key => $value) {
                    $array_time[$key] = dechex($value); //10=>16进制
                    if (strlen($array_time[$key]) == 1) {
                        $array_time[$key] = '0' . $array_time[$key]; //补齐16进制的0
                    }
                }
                $hextime = strtoupper(implode($array_time)); //16进制时间
                $str_sum = 'A55A' . '16' . $code . $edition . '01' . $eid . $hextime . '0A';
                //hexdec dechex
                //校验和计算
                $str_arr = str_split($str_sum, 2); //截取两个一组
                $sum = 0;
                foreach ($str_arr as $key => $value) {
                    $str_arr[$key] = hexdec($value); //16=>10
                    $sum += $str_arr[$key];
                }
                $sum = strtoupper(substr(dechex($sum), -2));
                $returnstr = $str_sum . $sum . 'CC33C33C';

                Log::write('RETURN:--' . $returnstr, 'TCP_TOWER_register');
                return $returnstr;
                break;
            case '04': //帧类型 心跳请求
                //A55A0F0000040000393681CC33C33C
                //A5 5A 0F 00 00 04 00 00 39 36 81 CC33C33C
                $sum = strtoupper(substr(dechex(hexdec($sum)+1),-2));
                $returnstr = 'A55A' . '0F' . $code . $edition . '05' . $eid . $sum . 'CC33C33C';
                return $returnstr;
                break;
            case '06': //帧类型 实时数据
                //A55A 1F 00 00 06 00003936 009900950894000A00000004001E001E A7 CC33C33C
                Log::write('-head:' . $head . '-length:' . $length . '-code:' . $code . '-edition:' . $edition . '-type:' . $type . '-eid:' . $eid . '-sum:' . $sum . '-end:' . $end, 'TCP_TOWER_register');
                // $returnstr = 'A55A' . '0F' . $code . $edition . '07' . $eid . '0A' . 'CC33C33C';
                // Log::write('RETURN:--' . $returnstr, 'TCP_INFO');
                $array_info = str_split($info, 2); //截取两个一组 19个元素
                /*
                "eid":"14853",
                "height":50,
                "weight":11,
                "round": 11.86,
                "amplitude": 11.86,
                "wind_speed": 11.86,
                "moment": 11.86,
                "moment_percent": 11.86,
                "override": 11.86,
                "angle_x": 11.86,
                "angle_y": 11.86
                 */
                $insert_data = [
                    'eid' => hexdec($eid),
                    'height' => round(hexdec($array_info[0] . $array_info[1]) / 10, 1), //高度
                    'weight' => round(hexdec($array_info[2] . $array_info[3]) / 10, 1), //重量
                    'round' => round(hexdec($array_info[4] . $array_info[5]) / 10, 1), //回转
                    'amplitude' => round(hexdec($array_info[6] . $array_info[7]) / 10, 1), //幅度
                    'wind_speed' => round(hexdec($array_info[8] . $array_info[9]) / 10, 1), //风速
                    'moment' => round(hexdec($array_info[10] . $array_info[11]) / 100, 2), //力矩
                    'angle_x' => round(hexdec($array_info[12] . $array_info[13]) / 100, 2), //倾角X
                    'angle_y' => round(hexdec($array_info[14] . $array_info[15]) / 100, 2), //倾角Y
                ];
                Log::write($insert_data, 'TCP_TOWER_register');
                /* 定义模型 */
                $TowerCraneRdata = new TowerCraneRdata;
                $TowerCraneNdata = TowerCraneNdata::where('eid', $insert_data['eid'])->find(); //最新一条数据
                if (!$TowerCraneNdata) {
                    $TowerCraneNdata = new TowerCraneNdata;
                }
                foreach ($insert_data as $key => $value) {
                    $TowerCraneRdata->$key = $value;
                    $TowerCraneNdata->$key = $value;
                }
                Log::write($TowerCraneNdata, 'TCP_TOWER_register');
                $TowerCraneNdata->update_time = date('Y-m-d H:i:s', time());
                $re = $TowerCraneRdata->save();
                $re = $TowerCraneNdata->save();
                // return $returnstr;
                break;
            case '08': //帧类型 工作循环数据
                //eid 12050024
                //A55A 23 00 00 08 00B7DE68 160A150F2C38003A01380BB0160A150F2D01003A014B0BAF000000240005 27 CC33C33C
                Log::write('-head:' . $head . '-length:' . $length . '-code:' . $code . '-edition:' . $edition . '-type:' . $type . '-eid:' . $eid . '-sum:' . $sum . '-end:' . $end, 'TCP_TOWER_register');
                // $returnstr = 'A55A' . '0F' . $code . $edition . '07' . $eid . '0A' . 'CC33C33C';
                // Log::write('RETURN:--' . $returnstr, 'TCP_INFO');
                $array_info = str_split($info, 2); //截取两个一组 30个元素
                /*
                "eid":"14853",
                "height":50,
                "weight":11,
                "round": 11.86,
                "amplitude": 11.86,
                "wind_speed": 11.86,
                "moment": 11.86,
                "moment_percent": 11.86,
                "override": 11.86,
                "angle_x": 11.86,
                "angle_y": 11.86
                 */
                $insert_data = [
                    'eid' => hexdec($eid),
                    'start_time' => '20'.hexdec($array_info[0]).'-'.hexdec($array_info[1]).'-'.hexdec($array_info[2]).' '.hexdec($array_info[3]).':'.hexdec($array_info[4]).':'.hexdec($array_info[5]), //时间
                    'start_height' => round(hexdec($array_info[6] . $array_info[7]) / 10, 1), //高度
                    'start_range' => round(hexdec($array_info[8] . $array_info[9]) / 10, 1), //幅度
                    'start_rotation_angle' => round(hexdec($array_info[10] . $array_info[11]) / 10, 1), //回转
                    'end_time' => '20'.hexdec($array_info[12]).'-'.hexdec($array_info[13]).'-'.hexdec($array_info[14]).' '.hexdec($array_info[15]).':'.hexdec($array_info[16]).':'.hexdec($array_info[17]), //时间
                    'end_height' => round(hexdec($array_info[18] . $array_info[19]) / 10, 1), //高度
                    'end_range' => round(hexdec($array_info[20] . $array_info[21]) / 10, 1), //幅度
                    'end_rotation_angle' => round(hexdec($array_info[22] . $array_info[23]) / 10, 1), //回转
                    'weight' => round(hexdec($array_info[24] . $array_info[25]) / 100, 1), //重量
                    'moment_percent' => round(hexdec($array_info[26] . $array_info[27]) / 10, 1), //力矩
                    'wind_speed' => round(hexdec($array_info[28] . $array_info[29]) / 10, 1), //风速
                ];
                Log::write($insert_data, 'TCP_TOWER_register');
                /* 定义模型 */
                $TowerCraneWorkData = new TowerCraneWorkData;
                foreach ($insert_data as $key => $value) {
                    $TowerCraneWorkData->$key = $value;
                }
                $re = $TowerCraneWorkData->save();
                // return $returnstr;
                break;
            case '0A': //帧类型 报警数据
                //A55A 1F 00 00 06 00003936 009900950894000A00000004001E001E A7 CC33C33C
                //A55A 20 00 00 0A 00003936 009900950895000A000001F2001E001E05 A1 CC33C33C
                Log::write('-head:' . $head . '-length:' . $length . '-code:' . $code . '-edition:' . $edition . '-type:' . $type . '-eid:' . $eid . '-sum:' . $sum . '-end:' . $end, 'TCP_INFO');
                // $returnstr = 'A55A' . '0F' . $code . $edition . '07' . $eid . '0A' . 'CC33C33C';
                // Log::write('RETURN:--' . $returnstr, 'TCP_INFO');
                $array_info = str_split($info, 2); //截取两个一组 19个元素
                /*
                "eid":"14853",
                "height":50,
                "weight":11,
                "round": 11.86,
                "amplitude": 11.86,
                "wind_speed": 11.86,
                "moment": 11.86,
                "moment_percent": 11.86,
                "override": 11.86,
                "angle_x": 11.86,
                "angle_y": 11.86
                 */
                $insert_data = [
                    'eid' => hexdec($eid),
                    'height' => round(hexdec($array_info[0] . $array_info[1]) / 10, 1), //高度
                    'weight' => round(hexdec($array_info[2] . $array_info[3]) / 10, 1), //重量
                    'round' => round(hexdec($array_info[4] . $array_info[5]) / 10, 1), //回转
                    'amplitude' => round(hexdec($array_info[6] . $array_info[7]) / 10, 1), //幅度
                    'wind_speed' => round(hexdec($array_info[8] . $array_info[9]) / 10, 1), //风速
                    'moment' => round(hexdec($array_info[10] . $array_info[11]) / 100, 2), //力矩
                    'angle_x' => round(hexdec($array_info[12] . $array_info[13]) / 100, 2), //倾角X
                    'angle_y' => round(hexdec($array_info[14] . $array_info[15]) / 100, 2), //倾角Y
                    'angle_y' => round(hexdec($array_info[14] . $array_info[15]) / 100, 2), //倾角Y
                    'alarm_type' => hexdec($array_info[16]), //倾角Y
                ];
                Log::write($insert_data, 'TCP_INFO');
                /* 定义模型 */
                $TowerAlarmRdata = new TowerAlarmRdata;
                $TowerAlarmNdata = TowerAlarmNdata::where('eid', $insert_data['eid'])->find(); //最新一条数据
                if (!$TowerAlarmNdata) {
                    $TowerAlarmNdata = new TowerAlarmNdata;
                }
                foreach ($insert_data as $key => $value) {
                    $TowerAlarmRdata->$key = $value;
                    $TowerAlarmNdata->$key = $value;
                }
                $re = $TowerAlarmRdata->save();
                $re = $TowerAlarmNdata->save();
                // return $returnstr;
                break;
            default:
                break;
        }
    }
    public static function tcpElevatorData($param, $client_id)
    {
        //拆分信息字段
        $head = substr($param, 0, 4);
        $length = substr($param, 4, 2); //帧长度 全部长度总和
        $code = substr($param, 6, 2); //厂家编号
        $edition = substr($param, 8, 2); //协议版本
        $type = substr($param, 10, 2); //帧类型
        $eid = substr($param, 12, 8); //设备编号
        $info = substr($param, 20, -10); //信息段
        $sum = substr($param, -10, 2); //校验和剔除sum end后的长度
        $end = substr($param, -8);
        Log::write('TCP_DATA:-head:' . $head . '-length:' . $length . '-code:' . $code . '-edition:' . $edition . '-type:' . $type . '-eid:' . $eid . '-info:' . $info . '-sum:' . $sum . '-end:' . $end, 'TCP_INFO');
        switch ($type) {
            case '00': //帧类型 设备注册请求帧上传
                //A5 5A 0F 00 00 00 00 00 39 36 -- 7D CC33C33C
                //A5 5A 16 00 00 01 00 00 39 36 16 09 1D 11 00 05 0A e1 CC33C33C
                //A5 5A 16 00 00 01 00 00 39 36 -- 16 09 1D 10 34 09 0A 21 -- 8C C33C33C
                Log::write('-head:' . $head . '-length:' . $length . '-code:' . $code . '-edition:' . $edition . '-type:' . $type . '-eid:' . $eid . '-sum:' . $sum . '-end:' . $end, 'TCP_INFO');
                $time = date('ymdHis', time()); //获取当前时间 转化为 年(2位)月日时分秒
                $array_time = str_split($time, 2); //截取两个一组
                foreach ($array_time as $key => $value) {
                    $array_time[$key] = dechex($value); //10=>16进制
                    if (strlen($array_time[$key]) == 1) {
                        $array_time[$key] = '0' . $array_time[$key]; //补齐16进制的0
                    }
                }
                $hextime = strtoupper(implode($array_time)); //16进制时间
                $str_sum = 'A55A' . '16' . $code . $edition . '01' . $eid . $hextime . '0A';
                //hexdec dechex
                //校验和计算
                $str_arr = str_split($str_sum, 2); //截取两个一组
                $sum = 0;
                foreach ($str_arr as $key => $value) {
                    $str_arr[$key] = hexdec($value); //16=>10
                    $sum += $str_arr[$key];
                }
                $sum = strtoupper(substr(dechex($sum), -2));
                $returnstr = $str_sum . $sum . 'CC33C33C';

                Log::write('RETURN:--' . $returnstr, 'TCP_INFO');
                return $returnstr;
                break;
            case '04': //帧类型 心跳请求
                //A55A 0F 00 00 04 000038A8 0A CC33C33C
                //A55A0F000004000038A80ACC33C33C
                $type = '05'; //帧类型 设备注册响应帧下传
                $returnstr = 'A55A' . '0F' . $code . $edition . $type . $eid . '11' . 'CC33C33C';
                // Log::write($returnstr, 'TCP');
                return $returnstr;
                break;
            case '06': //帧类型 实时数据
                //A55A 22 00 00 06 01504DD1 0000000000--0000000000--0000000000--00000000 1D CC33C33C
                //A55A2200000601504DD1 0001 0002 0000 0000 0000 0000 0063 00 00 00 00 00 1DCC33C33C
                //A55A2200000601504DD1000100020000000000000000006300000000001DCC33C33C
                //-head:A55A-length:22-code:00-edition:00-type:06-eid:01504DD1-info:00000000000000000000000000000000000000-sum:1D-end:CC33C33C
                $type = '07'; //帧类型 设备注册响应帧下传
                $length = '0F';
                $sum = '0A';
                Log::write('-head:' . $head . '-length:' . $length . '-code:' . $code . '-edition:' . $edition . '-type:' . $type . '-eid:' . $eid . '-sum:' . $sum . '-end:' . $end, 'TCP_INFO');
                $returnstr = 'A55A' . '0F' . $code . $edition . $type . $eid . '0A' . 'CC33C33C';
                Log::write('RETURN:--' . $returnstr, 'TCP_INFO');

                $array_info = str_split($info, 2); //截取两个一组 19个元素
                $insert_data = [
                    'eid' => hexdec($eid),
                    'height' => round(hexdec($array_info[0] . $array_info[1]) / 10, 1),
                    'weight' => round(hexdec($array_info[2] . $array_info[3]) / 10, 1),
                    'speed' => round(hexdec($array_info[4] . $array_info[5]) / 10, 1),
                    'wind_speed' => round(hexdec($array_info[6] . $array_info[7]) / 10, 1),
                    'elevator_load' => hexdec($array_info[8] . $array_info[9]),
                    'tilt_x' => hexdec($array_info[10] . $array_info[11]),
                    'tilt_y' => hexdec($array_info[12] . $array_info[13]),
                    'number' => hexdec($array_info[14]),
                    'front_door_status' => hexdec($array_info[15]),
                    'back_door_status' => hexdec($array_info[16]),
                    'top_door_status' => hexdec($array_info[17]),
                    'run_status' => hexdec($array_info[18]),
                ];
                Log::write($insert_data, 'TCP_INFO');
                /* 定义模型 */
                $ElevatorRdata = new ElevatorRdata;
                $ElevatorNdata = ElevatorNdata::where('eid', $insert_data['eid'])->find(); //最新一条数据
                if (!$ElevatorNdata) {
                    $ElevatorNdata = new ElevatorNdata;
                }
                foreach ($insert_data as $key => $value) {
                    $ElevatorRdata->$key = $value;
                    $ElevatorNdata->$key = $value;
                }
                $re = $ElevatorRdata->save();
                $re = $ElevatorNdata->save();
                // return null;
                return $returnstr;
                break;
            case '0A': //帧类型 报警数据
                //A55A 22 00 00 0A 01504DD1 0000000000--0000000000--0000000000--00000000 1D CC33C33C
                //A55A2200000A01504DD1 0001 0002 0000 0000 0000 0000 0063 00 00 00 00 00 03 1DCC33C33C
                //A55A2200000A01504DD100010002000000000000000000630000000000031DCC33C33C
                //-head:A55A-length:22-code:00-edition:00-type:06-eid:01504DD1-info:00000000000000000000000000000000000000-sum:1D-end:CC33C33C
                $type = '0B'; //帧类型 设备注册响应帧下传
                $length = '0F';
                $sum = '0A';
                Log::write('-head:' . $head . '-length:' . $length . '-code:' . $code . '-edition:' . $edition . '-type:' . $type . '-eid:' . $eid . '-sum:' . $sum . '-end:' . $end, 'TCP_INFO');
                $returnstr = 'A55A' . '0F' . $code . $edition . $type . $eid . '0A' . 'CC33C33C';
                Log::write('RETURN:--' . $returnstr, 'TCP_INFO');

                $array_info = str_split($info, 2); //截取两个一组 20个元素
                $insert_data = [
                    'eid' => hexdec($eid),
                    'height' => round(hexdec($array_info[0] . $array_info[1]) / 10, 1),
                    'weight' => round(hexdec($array_info[2] . $array_info[3]) / 10, 1),
                    'speed' => round(hexdec($array_info[4] . $array_info[5]) / 10, 1),
                    'wind_speed' => round(hexdec($array_info[6] . $array_info[7]) / 10, 1),
                    'elevator_load' => hexdec($array_info[8] . $array_info[9]),
                    'tilt_x' => hexdec($array_info[10] . $array_info[11]),
                    'tilt_y' => hexdec($array_info[12] . $array_info[13]),
                    'number' => hexdec($array_info[14]),
                    'front_door_status' => hexdec($array_info[15]),
                    'back_door_status' => hexdec($array_info[16]),
                    'top_door_status' => hexdec($array_info[17]),
                    'run_status' => hexdec($array_info[18]),
                    'type_id' => hexdec($array_info[19]),
                ];
                Log::write($insert_data, 'TCP_INFO');
                /* 定义模型 */
                $ElevatorAlarmRdata = new ElevatorAlarmRdata;
                $ElevatorAlarmNdata = ElevatorAlarmNdata::where('eid', $insert_data['eid'])->find(); //最新一条数据
                if (!$ElevatorAlarmNdata) {
                    $ElevatorAlarmNdata = new ElevatorAlarmNdata;
                }
                foreach ($insert_data as $key => $value) {
                    $ElevatorAlarmRdata->$key = $value;
                    $ElevatorAlarmNdata->$key = $value;
                }
                $re = $ElevatorAlarmRdata->save();
                $re = $ElevatorAlarmNdata->save();
                return $returnstr;
                break;

            default:
                return 0;
                break;
        }

    }
}
